package apiserver

import (
    "context"
    "fmt"
    "net/http"

    "github.com/gin-gonic/gin"
    log "github.com/sirupsen/logrus"

    "cing.io/cing-api/test"
    "cing.io/cing/internal/apiserver/routers"
    "cing.io/cing/internal/config"
)

func InitAPIServer(ctx context.Context) {
    engine := gin.New()
    engine.Use(gin.Recovery())

    v1Group := engine.Group("/v1")

    routers.InitRoutes(v1Group)

    // healthy check
    engine.GET("/healthz", func(c *gin.Context) {
        c.String(200, "ok")
    })

    engine.POST("/greet", func(c *gin.Context) {
        greet := test.GreetRequest{}
        if err := c.BindJSON(&greet); err != nil {
            c.Status(400)
            return
        }
        c.JSON(200, test.GreetResponse{Message: "Hello, " + greet.Name})
    })

    port := config.APIServerPort
    srv := &http.Server{
        Addr:    fmt.Sprintf(":%d", port),
        Handler: engine,
    }

    // Initializing the server in a goroutine so that
    // it won't block the graceful shutdown handling below
    go func() {
        <-ctx.Done()

        // Listen for the interrupt signal.
        if err := srv.Shutdown(context.Background()); err != nil {
            log.Fatal("Server forced to shutdown: ", err)
        }
    }()

    log.Info("API Server listening at: ", port)
    if err := srv.ListenAndServe(); err != nil {
        log.Fatalf("listen error: %s\n", err)
    }

    log.Println("Server exit!!!")
}
